package org.jeecg.activiti.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.UnsupportedEncodingException;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.jeecg.activiti.entity.ActReModelExtend;
import org.jeecg.activiti.service.IActReModelExtendService;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.apache.commons.codec.binary.Base64;

/**
 * 流程设计管理
 */
@RestController
@RequestMapping("/activiti/flow")
@Api(tags = "流程设计管理")
public class ActivitiFlowController {

	@Autowired
	private RepositoryService repositoryService;

	@Autowired
	private IActReModelExtendService iActReModelExtendService;

	@GetMapping("/getFlowByModelId")
	@ApiOperation(value = "根据流程定义ID查询流程", notes = "根据流程定义ID查询流程")
	public Result<Object> getFlowByModelId(
			@ApiParam(name = "modelId", value = "模型定义ID", required = true) @RequestParam(name = "modelId", required = true) String modelId) {
		try {
			byte[] flowByte = repositoryService.getModelEditorSource(modelId);
			String json_xml = new String(flowByte, "utf-8");
			return Result.OK(json_xml);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return Result.error("查询异常，请联系管理员。");
		}
	}

	/**
	 * 保存流程设计
	 * 
	 * @return
	 */
	@PostMapping("/saveFlow")
	@ApiOperation(value = "流程设计保存", notes = "流程设计保存")
	public Result<Object> saveFlow(@RequestBody JSONObject jsonObject) {
		try {
			String modelId = jsonObject.getString("modelId");
			String jsonXml = jsonObject.getString("json_xml");
			String svgXml = jsonObject.getString("svg_xml");

			Model model = repositoryService.getModel(modelId);

			repositoryService.addModelEditorSource(model.getId(), jsonXml.getBytes("utf-8"));

			final byte[] result = new Base64().decode(svgXml);
			repositoryService.addModelEditorSourceExtra(model.getId(), result);

			iActReModelExtendService
					.update(new UpdateWrapper<ActReModelExtend>().set("status", 0).eq("model_id", modelId));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return Result.OK();
	}

}
